from fontTools.ttLib import TTFont
from lxml import etree

# 第1步：获取html，且存为html文件以便后面研究使用

# 第2步：下载html配套的ttf文件

# 第3步：提取ttf中摄影的数据
font = TTFont("./实习憎.ttf")
cmap = font.get("cmap").getBestCmap()
# print(cmap)
ttf_dict = dict()
for k, v in cmap.items():
    # print(k, v)  # 原样数据
    # print(hex(k), v)  # 转换为十六进制
    if v[3:]:
        # 1. 提取
        # print(hex(k), "\\u00" + v[3:] if len(v[3:]) == 2 else "\\u" + v[3:])
        # 2. 转换为真正的字
        content = "\\u00" + v[3:] if len(v[3:]) == 2 else "\\u" + v[3:]
        real_content = content.encode('utf-8').decode('unicode_escape')
        # print(hex(k), real_content)
        # 3. 替换k
        k_hex = hex(k)
        real_k = k_hex.replace("0x", "&#x")
        # print(real_k, real_content)
        # 4. 封装为字典
        ttf_dict[real_k] = real_content

print("解析后：", ttf_dict)

# 第4步：对下载的实习憎文件（即HTML内容）进行替换
with open("实习憎.html", "r") as f:
    html = f.read()

    for k, v in ttf_dict.items():
        html = html.replace(k, v)

    # print("替换之后的HTML：")
    # print(html)

# 第5步：使用xpath提取想要的数据
html = etree.HTML(html)
li_list = html.xpath("//div[@class='intern-wrap intern-item']")
# print(li_list)
for li in li_list:
    title = "".join(li.xpath(".//div[@class='f-l intern-detail__job']//a/text()")[0].split())
    price = "".join(li.xpath(".//div[@class='f-l intern-detail__job']//span[@class='day font']/text()")[0].split())
    print(title, price)
